//
//  YFOAuthViewController.swift
//  仿新浪微博
//
//  Created by 杨帆 on 16/7/3.
//  Copyright © 2016年 杨帆. All rights reserved.
//

import UIKit
import SVProgressHUD

// 通过 webView 加载新浪微博授权页面控制器
class YFOAuthViewController: UIViewController {

    private lazy var webView = UIWebView()
    
    override func loadView() {
        
        view = webView
        
        view.backgroundColor = UIColor.white()
        
        // 设置导航栏
        title = "登录新浪微博"
        
        // 取消滚动视图
        webView.scrollView.isScrollEnabled = false
        
        // 设置代理
        webView.delegate = self
        
        // 导航栏按钮
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "返回", target: self, action: #selector(close), isBack: true)
        
        // 添加自动填充按钮
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动输入", target: self, action: #selector(autoFill))
        

    }
    
    override func viewDidLoad() {
        super.viewDidLoad()

        // 加载授权请求
        let urlString = "https://api.weibo.com/oauth2/authorize?client_id=\(YFAppKey)&redirect_uri=\(YFRedirectURI)"
        // URL 确定要访问的资源
        guard let url = URL(string: urlString) else {
        
            return
        }
        
        // 建立请求
        let request = URLRequest(url: url)
        
        // 加载请求
        webView.loadRequest(request)
        
    }

    

// MARK: - 监听方法
    
    // 关闭控制器
    @objc private func close() {
        SVProgressHUD.dismiss()
    
        dismiss(animated: true, completion: nil)
    }
// MARK: - 自动填充
    @objc private func autoFill() {
        
        let js = "document.getElementById('userId').value = '18810878277';" +
        "document.getElementById('passwd').value = 'fuck2015';"
        
        webView.stringByEvaluatingJavaScript(from: js)
        
    }

}
// MARK: - UIWebViewDelegate
extension YFOAuthViewController: UIWebViewDelegate {
    
    func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        
        // 如果请求地址包含 baidu.com 不加载页面 否则加载页面
        if request.url?.absoluteString?.hasPrefix(YFRedirectURI) == false {
        
            return true
            
        }
        
        // 如果有 授权成功 否则 授权失败
        if request.url?.query?.hasPrefix("code=") == false {
            
            print("取消授权")
            close()
            
            return false
        }
        
        //从query 字符串中取出授权码
        let code = request.url?.query?.substring(from: "code=".endIndex) ?? ""
        
        print("授权码 - \(code)")
        
        // 使用授权码获取AccessToken
        YFNetWorkManager.shared.loadAccessToken(code: code) { (isSuccess) in
            
            if !isSuccess {
            SVProgressHUD.showInfo(withStatus: "网络请求失败")
                
            } else {
            
                
                // 下一步做什么 跳转界面 如何跳转?（通过发送东路成功消息）
                // 1> 发送通知 不关心有没有监听者
                NotificationCenter.default.post(
                
                    name: NSNotification.Name(rawValue: YFUserShouldLoginSuccessedNotification),
                    object: nil)
                
                // 2> 关闭窗口
                self.close()
                
            }
        
        }
        
        return true
    }

    func webViewDidStartLoad(_ webView: UIWebView) {
        
        
        SVProgressHUD.show()
    }
    
    func webViewDidFinishLoad(_ webView: UIWebView) {
        
        SVProgressHUD.dismiss()
    }
}
